<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <textarea class="cmt-content" name="" id="" style="width: 100%; height: 90px" placeholder="随便写点什么" maxlength="120" v-model="userInput"></textarea>
    <button type="button" class="mui-btn mui-btn-block mui-btn-primary" @click="postComment">确认发表</button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="item in comments" :key="item.add_time">
        <div class="cmt-title">
          用户: {{item.user_name}} 发表时间: {{item.add_time | dateFormat}}
        </div>
        <div class="cmt-content">
          {{item.content}}
        </div>
      </div>
    </div>
    <button type="button" class="mui-btn mui-btn-block mui-btn-primary" @click="getMore">加载更多</button>
  </div>
</template>

<script>
import {Toast} from 'mint-ui'
import axios from 'axios'
export default {
  props: ['id'],
  data() {
    return {
      pageIndex: 1,
      comments: [],
      userInput: []
    }
  },
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      axios.get('http://www.lovegf.cn:8899/api/getcomments/' + this.id + '?pageindex=' + this.pageIndex).then(res => {
        if (res.data.status === 0) {
          // console.log(res.data.message);
          // this.comments = res.data.message
          this.comments = this.comments.concat(res.data.message);
          Toast(`更新了${res.data.message.length}条留言`)
        } else {
          Toast('获取评论失败!')
        }
      })
    },
    getMore() {
      this.pageIndex++;
      var origin = this.comments;
      this.getComments();
    },
    postComment() {
      if (this.userInput.trim().length === 0) {
        Toast('评论内容不能为空')
      }
      axios.post('http://www.lovegf.cn:8899/api/postcomment/' + this.$route.params.id).then(res => {
        if (res.data.status === 0) {
          var post_cmt = {
            user_name: '佚名',
            add_time: Date.now(),
            content: this.userInput.trim()
          }
          this.comments.unshift(post_cmt);
          this.userInput = '';
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .cmt-container {
    .cmt-content {
      font-size: 13px
    }
    .cmt-list {
      margin: 10px auto;
      font-size: 13px;
      .cmt-title {
        background-color: #c2c3ec;
        line-height: 30px;
      }
      .cmt-content {
        line-height: 36px;
        text-indent: 2em;
      }
    }
    .mui-btn-primary {
      &:nth-of-type(2) {
        padding: 10px 0;
        background-color: #fff;
        border: 1px dashed #a93f5e;
        color: #777;
      }
    }
  }
  
</style>
